﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Data.Common;
using System.Data;

namespace com.byt.webcore
{
    public class Connection
    {
        internal DbConnection conn=null;
        private DbTransaction transaction=null;

        public Connection(DbConnection conn)
        {
            this.conn = conn;
        }

        public DbTransaction Transaction
        {
            get { return transaction; }
        }

        public DbTransaction BeginTransaction()
        {
            if (transaction != null)
                throw new Exception("La transacción ya esta abierta.");

            transaction = conn.BeginTransaction();
            return transaction;
        }

        public DbTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            if (transaction != null)
                throw new Exception("La transacción ya esta abierta.");

            transaction = conn.BeginTransaction(isolationLevel);
            return transaction;
        }

        public void Commit()
        {
            if (transaction == null)
                return;
            transaction.Commit();
            transaction = null;
            //BeginTransaction();
        }

        public void Rollback()
        {
            if (transaction == null)
                return;
            transaction.Rollback();
            transaction = null;
            //BeginTransaction();
        }

        public DbCommand CreateCommand()
        {
            DbCommand cmd = conn.CreateCommand();
            if (transaction != null)
                cmd.Transaction = transaction;

            return cmd;
        }


        public void Close()
        {
            Commit();
            conn.Close();
        }
    }
}